import cv2
import numpy as np

filename = 'lena.bmp'
src = cv2.imread(filename, cv2.IMREAD_COLOR)
image = src
winname = 'Adjust HSV'

# 修改图像HSV
def change_HSV(pos):
    global image
    dh = cv2.getTrackbarPos('H', winname) * 255 / 360
    ds = cv2.getTrackbarPos('S', winname) - 255
    dv = cv2.getTrackbarPos('V', winname) - 255

    hsv = cv2.cvtColor(src, cv2.COLOR_RGB2HSV_FULL)
    hsv = hsv.astype(np.float32)
    h, s, v = cv2.split(hsv)

    h = (h + dh) % 255

    s += ds
    s[s > 255] = 255
    s[s < 0] = 0

    v += dv
    v[v > 255] = 255
    v[v < 0] = 0

    hsv = cv2.merge((h, s, v))
    hsv = hsv.astype(np.uint8)
    image = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB_FULL)


# 创建一个命名窗口
cv2.namedWindow(winname)
# 创建HSV滑杆
cv2.createTrackbar('H', winname, 0, 360, change_HSV)
cv2.createTrackbar('S', winname, 0, 512, change_HSV)
# 因为OpenCV滑杆不支持负数, S滑杆只好以255为0
cv2.setTrackbarPos('S', winname, 255)
cv2.createTrackbar('V', winname, 0, 512, change_HSV)
# 因为OpenCV滑杆不支持负数, V滑杆只好以255为0
cv2.setTrackbarPos('V', winname, 255)

while True:
    cv2.imshow(winname, image)
    key = cv2.waitKey(1)
    if key == ord(chr(27)):
        break

cv2.destroyAllWindows()
